import 'package:bluetooth_protocols_parser_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:lx_widgets_library/text/lx_text.dart';

import '../../../../l10n/local.dart';
import '../../../models/firmware_info_model.dart';
import '../../../others/common_enum/firmware_update_type.dart';
import 'controller.dart';

class OtaView extends BaseGetView<OtaController> {
  OtaView({super.key});

  @override
  String get title => local.vehicle_settings;

  @override
  List<Widget>? get rightViews => [
        Obx(
          () {
            return Visibility(
              visible: !controller.state.isUpdatingAll.value &&
                  controller.state.currentUpdatingModels.isNotEmpty,
              child: Padding(
                padding: EdgeInsets.only(right: CONTENT_MARGIN / 2),
                child: LxButton(
                  onTap: () {
                    controller.updateAllFirmware();
                  },
                  title: local.one_key_upgrade,
                  buttonTypeCustomColor: ButtonTypeColor()
                    ..backgroundColor = Colors.transparent
                    ..borderColor = Colors.transparent
                    ..textColor = LxCol.theme,
                ),
              ),
            );
          },
        ),
      ];

  @override
  Widget buildBody(BuildContext context) {
    return Material(
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Obx(
          () {
            return Column(
              children: [
                // 顶部统计信息
                _buildStatsCard(),
                SizedBox(height: CONTENT_MARGIN),
                // 设备列表
                Expanded(
                  child: ListView.builder(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    itemCount: controller.state.currentUpdatingModels.length,
                    itemBuilder: (context, index) {
                      return _buildDeviceCard(
                          controller.state.currentUpdatingModels[index]);
                    },
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildStatsCard() {
    final totalDevices = controller.state.currentUpdatingModels.length;
    final upToDateDevices = controller.state.currentUpdatingModels
        .where((d) => d.status.value == UpgradeStatus.upToDate)
        .length;
    final updateAvailableDevices = controller.state.currentUpdatingModels
        .where((d) =>
            d.status.value == UpgradeStatus.updateAvailable ||
            d.status.value == UpgradeStatus.downgradeAvailable)
        .length;
    final failedDevices = controller.state.currentUpdatingModels
        .where((d) => d.status.value == UpgradeStatus.updateFailed)
        .length;

    return Container(
      margin: EdgeInsets.all(CONTENT_MARGIN),
      padding: EdgeInsets.all(CONTENT_MARGIN),
      decoration: BoxDecoration(
        color: const Color(0xFF1D1E33),
        borderRadius: BorderRadius.circular(CONTENT_MARGIN),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem(
              local.total_devices, totalDevices.toString(), Colors.blue),
          _buildStatItem(
              local.updated_devices, upToDateDevices.toString(), Colors.green),
          _buildStatItem(local.upgradable_devices,
              updateAvailableDevices.toString(), Colors.orange),
          _buildStatItem(local.failed, failedDevices.toString(), Colors.red),
        ],
      ),
    );
  }

  Widget _buildStatItem(String title, String value, Color color) {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.all(CONTENT_MARGIN / 2),
          decoration: BoxDecoration(
            color: color.withOpacity(0.2),
            shape: BoxShape.circle,
          ),
          child: Text(
            value,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ),
        SizedBox(height: CONTENT_MARGIN / 2),
        Text(
          title,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  Widget _buildDeviceCard(FirmwareInfoModel device) {
    return Container(
      margin: EdgeInsets.only(bottom: CONTENT_MARGIN),
      padding: EdgeInsets.all(CONTENT_MARGIN),
      decoration: BoxDecoration(
        color: GrayColor.gray1,
        borderRadius: BorderRadius.circular(CONTENT_MARGIN),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            blurRadius: 10.w,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  _buildDeviceIcon(device.deviceType),
                  SizedBox(width: 12.w),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        device.deviceType?.name ?? "",
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        local.current_version(device.appVersion),
                        style: const TextStyle(
                          fontSize: 14,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              _buildStatusBadge(
                device.status.value,
                onTap: () {
                  controller.updateFirmware(device);
                },
              ),
            ],
          ),
          SizedBox(height: CONTENT_MARGIN),
          if (device.status.value == UpgradeStatus.updateAvailable ||
              device.status.value == UpgradeStatus.downgradeAvailable)
            Row(
              children: [
                const Icon(
                  Icons.new_releases,
                  color: Colors.orange,
                  size: 16,
                ),
                SizedBox(width: 4.w),
                Text(
                  local.new_version(device.latestVersion.value),
                  style: const TextStyle(
                    color: Colors.orange,
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          if (device.status.value == UpgradeStatus.updating) ...[
            SizedBox(height: 12.w),
            Obx(
              () => LinearProgressIndicator(
                value: device.progress / 100,
                backgroundColor: Colors.grey[800],
                valueColor:
                    const AlwaysStoppedAnimation<Color>(Colors.blueAccent),
              ),
            ),
            SizedBox(height: CONTENT_MARGIN / 2),
            Obx(
              () => Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    device.progressDescription.value,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.blueAccent,
                    ),
                  ),
                  Text(
                    '${device.progress}%',
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.blueAccent,
                    ),
                  ),
                ],
              ),
            ),
          ],
          if ((device.status.value == UpgradeStatus.updateAvailable ||
                  device.status.value == UpgradeStatus.downgradeAvailable) &&
              !controller.state.isUpdatingAll.value)
            Row(
              children: [
                Expanded(
                  child: LxText(
                    device.updateDescription.value,
                    fontWeightEnum: LxFontWeightEnum.bodySmall,
                    color: Colors.white.withOpacity(0.6),
                    lineHeight: 1.3,
                  ),
                ),
                ElevatedButton(
                  onPressed: () {
                    controller.updateFirmware(device);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blueAccent,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Text(
                    local.update_now,
                  ),
                ),
              ],
            )
        ],
      ),
    );
  }

  Widget _buildDeviceIcon(TargetDeviceType? type) {
    IconData icon;
    Color color;

    switch (type) {
      case TargetDeviceType.eucBle:
        icon = Icons.bluetooth;
        color = Colors.blue;
        break;
      case TargetDeviceType.eucHmic:
        icon = Icons.touch_app;
        color = Colors.green;
        break;
      case TargetDeviceType.eucDriver:
        icon = Icons.directions_car;
        color = Colors.orange;
        break;
      case TargetDeviceType.scooterDisplay:
        icon = Icons.memory;
        color = Colors.purple;
        break;
      case TargetDeviceType.eucTBox:
        icon = Icons.cloud;
        color = Colors.cyan;
        break;
      case TargetDeviceType.eucBMS1:
      case TargetDeviceType.eucBMS2:
        icon = Icons.battery_std;
        color = Colors.greenAccent;
        break;
      case TargetDeviceType.eucDc:
        icon = Icons.screen_rotation;
        color = Colors.amber;
        break;
      default:
        icon = Icons.device_unknown;
        color = Colors.grey;
        break;
    }

    return Container(
      padding: EdgeInsets.all(CONTENT_MARGIN / 2),
      decoration: BoxDecoration(
        color: color.withOpacity(0.2),
        borderRadius: BorderRadius.circular(12.w),
      ),
      child: Icon(icon, color: color, size: 24),
    );
  }

  Widget _buildStatusBadge(UpgradeStatus status, {VoidCallback? onTap}) {
    String text;
    Color color;

    switch (status) {
      case UpgradeStatus.upToDate:
        text = local.latest_devices;
        color = Colors.green;
        break;
      case UpgradeStatus.updateAvailable:
        text = local.upgradable_devices;
        color = Colors.orange;
        break;
      case UpgradeStatus.downgradeAvailable:
        text = local.downgrade_available;
        color = Colors.orange;
        break;
      case UpgradeStatus.updating:
        text = local.updating;
        color = Colors.blueAccent;
        break;
      case UpgradeStatus.updateFailed:
        text = local.retry;
        color = Colors.red;
        break;
    }

    return InkWell(
      onTap: () {
        if (status == UpgradeStatus.updateFailed && onTap != null) {
          onTap();
        }
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: color.withOpacity(0.2),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Text(
          text,
          style: TextStyle(
            color: color,
            fontSize: 12,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}
